<?php
/**
 * TOP的客户端模型
 * 
 * @version $Id: TopSender.php 162 2011-12-08 06:23:41Z linsir123 $
 */
class TopSender
{
	/**
	 * @var 客户端实例
	 */
	public $client;
	
	/**
	 * @var 应用
	 */
	public $appkey;
	
	/**
	 * @var 应用密钥
	 */
	public $secretKey;
	
	/**
	 * @var Sesionkey
	 */
	public $sesionKey;
	
	/**
	 * 构造函数
	 */
	public function __construct($appkey = null)
	{
		$conf = App::O('taobaoke.keys');
		$count = count($conf);
		
		///
		if (empty($appkey)) {
			$i = $count > 1 ? mt_rand(0, $count - 1) : 0;
			$this->appkey = $conf[$i][0];
			$this->secretKey = $conf[$i][1];
		} else {
			$this->appkey = $appkey;
			for ($i=0; $i<$count; $i++) {
				if ($conf[$i][0] == $appkey) {
					$this->secretKey = $conf[$i][1];
					break;
				}
			}
		}
	}
	
	/**
	 * 设置Sesionkey
	 */
	public function login($sesionKey)
	{
		$this->sesionKey = $sesionKey;
	}
	
	/**
	 * 执行请求
	 */
	public function execute($request, $format = 'json')
	{
		$client = $this->getClient($format);
		$client->format = $format;
		
		///
		return $client->execute($request, $this->sesionKey);
	}
	
	/**
	 * 请求客户端
	 */
	public function getClient()
	{
		if (empty($this->client)) {
			if ( ! class_exists('TopClient')) 
				App::V('taobao');
				
			///
			$this->client = App::singleton('TopClient');
			$this->client->secretKey = $this->secretKey;
			$this->client->appkey = $this->appkey;
		}
		
		return $this->client;
	}
}
